package util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;

public class UrlUtil {

    private static Set<String> domains = null;

    private static synchronized void initDomains() throws IOException {
        if (domains == null) {
            domains = new HashSet<String>();

            InputStream is = UrlUtil.class
                    .getResourceAsStream("util_domain.txt");
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            for (String line = br.readLine(); line != null; line = br
                    .readLine()) {
                line = line.trim();
                if (!line.isEmpty() && !line.startsWith("#")) {
                    domains.add(line);
                }
            }
            br.close();
        }
    }

    public static boolean isIPv4(String host) {
        String[] vals = host.trim().split("\\.");

        try {
            if (vals.length == 4) {
                for (String val : vals) {
                    int num = Integer.parseInt(val);
                    if (num < 0 || num > 255) {
                        return false;
                    }
                }
                return true;
            }
        } catch (Exception e) {
        }

        return false;
    }

    public static String getDomain(String url) throws IOException {
        if (domains == null) {
            initDomains();
        }

        int start = Math.max(0, url.indexOf("://") + 3);
        int end = (url + "/").indexOf("/", start);

        String host = url.substring(start, end);
        if (!host.isEmpty() && !host.contains("..")) {
            host = host.split(":")[0];
            if (!isIPv4(host)) {
                int pos = host.lastIndexOf('.');
                while (pos >= 0) {
                    String sub = host.substring(pos + 1);
                    if (!domains.contains(sub)) {
                        host = sub;
                        break;
                    }
                    pos = host.lastIndexOf('.', pos - 1);
                }
                if (host.startsWith("www.")) {
                    host = host.substring(4);
                }
            }
            return host;
        }
        return "";
    }

    public static String getHost(String url) {
        try {
            url = url + "/";
            url = url.replaceAll("\\?", "/\\?");
            url = url.replaceAll("=", "/=");
            return url.substring(0, url.indexOf("/", url.indexOf("://") + 3));
        } catch (Exception e) {
            return "";
        }
    }

}
